<script setup lang="ts">
import {computed, onMounted, type PropType, reactive} from 'vue';
import api from '@/api';
import type {AreaResChildType, AreaResType} from "@/types/address";

const props = defineProps({
  // 通过双向绑定控制组件的弹出与收起
  modelValue: {
    type: Boolean,
    default: false
  },
  // 默认显示的地区，可传类似["河北省", "秦皇岛市", "北戴河区"]
  defaultRegion: {
    type: Array as PropType<string[]>, // 明确是 number[]
    default () {
      return [];
    }
  },
  // 默认显示地区的编码，defaultRegion和areaCode同时存在，areaCode优先，可传类似["13", "1303", "130304"]
  areaCode: {
    type: Array as PropType<number[]>, // 明确是 number[]
    default () {
      return [];
    }
  },
  // 是否允许通过点击遮罩关闭Picker
  maskCloseAble: {
    type: Boolean,
    default: true
  },
  // 弹出的z-index值
  zIndex: {
    type: [String, Number],
    default: 0
  }
})
const emit = defineEmits(['city-change', 'update:modelValue'])

interface StateType {
  isChooseP: boolean;
  isChooseC: boolean;
  isChooseA: boolean;
  provinces: AreaResType; // 使用 AreaItem 类型
  citys: AreaResType;
  areas: AreaResType;
  province: AreaResChildType;
  city: AreaResChildType;
  area: AreaResChildType;
  tabsIndex: number;
}

const state = reactive<StateType>({
  isChooseP: false, //是否已经选择了省
  isChooseC: false, //是否已经选择了市
  isChooseA: false, //是否已经选择了区
  provinces: [], //省列表
  citys: [], //市列表
  areas: [], //区列表
  province: {value:0,label:''}, //当前选中的省
  city: {value:0,label:''}, //当前选中的市
  area: {value:0,label:''}, //当前选中的区
  tabsIndex: 0, // 当前选中的tab
})

const isChange = computed(() => state.tabsIndex > 1);

const genTabsList = computed(() => {
  let tabsList = [{
    name: "请选择"
  }];
  if (state.isChooseP) {
    tabsList[0]['name'] = state.province.label;
    tabsList[1] = {
      name: "请选择"
    };
  }
  if (state.isChooseC) {
    tabsList[1]['name'] = state.city.label;
    tabsList[2] = {
      name: "请选择"
    };
  }
  if (state.isChooseA) {
    tabsList[2]['name'] = state.area.label;
  }
  return tabsList;
});
const uZIndex = computed(() => {
  // 如果用户有传递z-index值，优先使用
  return props.zIndex ? props.zIndex : uni.$u.zIndex.popup;
});

const init = async () => {
  await api.common.getAreaApi().then((res:ApiResponse<AreaResType>) => {
    state.provinces = res.data || [] ;
  });
  if(props.areaCode.length===3){
    setProvince("", props.areaCode![0]);
    setCity("", props.areaCode![1]);
    setArea("", props.areaCode![2]);
  }else if(props.defaultRegion.length===3){
    setProvince(props.defaultRegion![0]);
    setCity(props.defaultRegion![1]);
    setArea(props.defaultRegion![2]);
  }
}
const setProvince = (label = "", value = 0) => {
  state.provinces.map((v)=>{
    if (value ? v.value == value : v.label == label) {
      provinceChange(v);
    }
  })
}
const setCity = (label = "", value = 0) => {
  state.citys.map((v)=>{
    if (value ? v.value == value : v.label == label) {
      cityChange(v);
    }
  })
}
const setArea = (label = "", value = 0) => {
  state.areas.map((v)=>{
    if (value ? v.value == value : v.label == label) {
      areaChange(v);
    }
  })
}
const provinceChange = async (item: AreaResChildType) => {
  state.isChooseP = true;
  state.isChooseC = false;
  state.isChooseA = false;
  await api.common.getAreaApi({province:item.value}).then((res:ApiResponse<AreaResType>) => {
    state.citys = res.data || [] ;
  });
  state.tabsIndex=1
  state.province = item;
}
const cityChange = async (item: AreaResChildType) => {
  state.isChooseC = true;
  state.isChooseA = false;
  await api.common.getAreaApi({province:state.province,city:item.value}).then((res:ApiResponse<AreaResType>) => {
    state.areas = res.data || [] ;
  });
  state.tabsIndex=2
  state.city = item;
}
const areaChange = (item: AreaResChildType) => {
  state.isChooseA = true;
  state.area = item;
  emit('city-change', {province:state.province,city:state.city,area:state.area});
  close();
}

const close = () => {
  emit('update:modelValue', false);
}
const tabsChange = (index: number) => {
  state.tabsIndex = index;
}
onMounted(()=>{
  init()
})


</script>

<template>
	<up-popup :show="modelValue" mode="bottom" :popup="false"
		:mask="true" :closeable="true" :safe-area-inset-bottom="true"
		close-icon-color="#ffffff" :z-index="uZIndex"
		:maskCloseAble="maskCloseAble" @close="close">
		<up-tabs v-if="modelValue" :list="genTabsList"
			:scrollable="true" :current="state.tabsIndex" @change="tabsChange" ref="tabs"></up-tabs>
		<view class="area-box">
			<view class="u-flex" :class="{ 'change':isChange }">
				<view class="area-item">
					<view class="u-padding-10 u-bg-gray" style="height: 100%;">
						<scroll-view :scroll-y="true" style="height: 100%">
							<up-cell-group>
								<up-cell v-for="(item,index) in state.provinces"
									:title="item.label" :arrow="false"
									:index="index" :key="index"
									@click="provinceChange(item)">
									<template v-slot:right-icon>
										<up-icon v-if="state.isChooseP&&state.province.value===item.value"
											size="17" name="checkbox-mark"></up-icon>
									</template>
								</up-cell>
							</up-cell-group>
						</scroll-view>
					</view>
				</view>
				<view class="area-item">
					<view class="u-padding-10 u-bg-gray" style="height: 100%;">
						<scroll-view :scroll-y="true" style="height: 100%">
							<up-cell-group v-if="state.isChooseP">
								<up-cell v-for="(item,index) in state.citys"
									:title="item.label" :arrow="false"
									:index="index" :key="index"
									@click="cityChange(item)">
									<template v-slot:right-icon>
										<up-icon v-if="state.isChooseC&&state.city.value===item.value"
											size="17" name="checkbox-mark"></up-icon>
									</template>
								</up-cell>
							</up-cell-group>
						</scroll-view>
					</view>
				</view>
				<view class="area-item">
					<view class="u-padding-10 u-bg-gray" style="height: 100%;">
						<scroll-view :scroll-y="true" style="height: 100%">
							<up-cell-group v-if="state.isChooseC">
								<up-cell v-for="(item,index) in state.areas"
									:title="item.label" :arrow="false"
									:index="index" :key="index"
									@click="areaChange(item)">
									<template v-slot:right-icon>
										<up-icon v-if="state.isChooseA&&state.area.value===item.value"
											size="17" name="checkbox-mark"></up-icon>
									</template>
								</up-cell>
							</up-cell-group>
						</scroll-view>
					</view>
				</view>
			</view>
		</view>
	</up-popup>
</template>

<style lang="scss">
	.area-box {
		width: 100%;
		overflow: hidden;
		height: 800rpx;

		>view {
			width: 150%;
			transition: transform 0.3s ease-in-out 0s;
			transform: translateX(0);

			&.change {
				transform: translateX(-33.3333333%);
			}
		}

		.area-item {
			width: 33.3333333%;
			height: 800rpx;
		}
	}
</style>
